﻿/**
 * 
 */
package dao;

import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import bean.Product;
import util.JdbcUtils;


public class productDao {
	
	/**
	 * 根据bid查询商品信息
	 * @param bid
	 * @return
	 */
	public static Product query(String bid) {
		String sql = "SELECT * FROM book WHERE bid=?";
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		//需要加个限制条件，放置bid为null
		try {
			conn = JdbcUtils.getConnection();
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, bid);
			rs = pstmt.executeQuery();
			if(rs.next()) {
				
				Product product = new Product(bid,rs.getString("author"),rs.getString("bname"),rs.getBigDecimal("price"),rs.getString("image"),rs.getString("pintro"));
				return product;
			}
			
		}catch(Exception e) {
			e.printStackTrace();
		}finally {
			try {
				rs.close();
				pstmt.close();
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			
		}
		return null;
	}
	
	
	public static Product[] queryPage(Integer intPage) {
		String sql = "SELECT * FROM book LIMIT 8 OFFSET ?;";
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		Product[] product = new Product[8];
		
		try {
			conn = JdbcUtils.getConnection();
			pstmt = conn.prepareStatement(sql);
			pstmt.setInt(1,(intPage-1)*8);
			rs = pstmt.executeQuery();
			int index = 0;
			while(rs.next()) {
				product[index] = new Product(rs.getString("bid"),rs.getString("author"),rs.getString("bname"),rs.getBigDecimal("price"),rs.getString("image"),rs.getString("pintro"));
				index++;
			}
			return product;
			
		}catch(Exception e) {
			e.printStackTrace();
		}finally {
			try {
				rs.close();
				pstmt.close();
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return null;
	}
}
